/*
package com.thread.threadfirst.marvel.citymaster.service;

import com.fugui.marvel.common.utils.StringUtils;
import com.fugui.marvel.service.citymaster.annotation.Log;
import com.fugui.marvel.service.citymaster.annotation.LogTypeEnum;
import com.fugui.marvel.service.citymaster.conf.PropertiesConfig;
import com.fugui.marvel.service.citymaster.entity.Query;
import com.fugui.marvel.service.citymaster.enums.ApplyCityStatus;
import com.fugui.marvel.service.citymaster.enums.ApplyCityType;
import com.fugui.marvel.service.citymaster.enums.CityConfigStatus;
import com.fugui.marvel.service.citymaster.mapper.ApplyCityMasterMapper;
import com.fugui.marvel.service.citymaster.mapper.CityConfigMapper;
import com.fugui.marvel.service.common.domain.user.TUser;
import com.fugui.marvel.service.common.dto.ReturnT;
import com.fugui.marvel.service.common.dto.citymaster.ApplyCityMasterDTO;
import com.fugui.marvel.service.common.dto.citymaster.CampaignListDTO;
import com.fugui.marvel.service.common.dto.citymaster.CityConfigDTO;
import com.fugui.marvel.service.common.dto.citymaster.CityDetailModel;
import com.fugui.marvel.service.common.service.feign.client.citymaster.FeignApplyCityMasterServiceClient;
import com.fugui.marvel.service.common.service.feign.client.notice.FeignNoticeSendClient;
import com.fugui.marvel.service.common.service.feign.client.user.FeignUserServiceClient;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.net.InetAddress;
import java.text.MessageFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static com.fugui.marvel.common.utils.DateUtilHelper.*;


*/
/**
 * @author yinwensheng
 * @date
 *//*

@Api("竞选城主Service")
@Service
@RestController
@Transactional(rollbackFor = Exception.class)
public class ApplyCityMasterServiceImpl implements FeignApplyCityMasterServiceClient {


    */
/**
     * log
     *//*

    private static final Logger log = LoggerFactory.getLogger(ApplyCityMasterServiceImpl.class);


    */
/**
     * user
     *//*

    @Autowired
    FeignUserServiceClient feignUserServiceClient;

    */
/**
     *
     *//*

    @Autowired
    ApplyCityMasterMapper applyCityMasterMapper;


    */
/**
     *
     *//*

    @Autowired
    CityConfigMapper cityConfigMapper;


    */
/**
     * 短信发送
     *//*

    @Autowired
    FeignNoticeSendClient feignNoticeSendClient;


    */
/**
     * redis
     *//*

    @Autowired
    RedisService feignRedisServiceClient;


    */
/**
     *
     *//*

    @Autowired
    PropertiesConfig propertiesConfig;


    */
/**
     * 筛选能够参与此活动的资格接口 --
     *//*

    @Log(prefix = "筛选能够参与此活动的资格接口", value = LogTypeEnum.ALL)
    @RequestMapping(method = RequestMethod.POST, value = "/m2.0/citymaster/save/applycitymaster/queryUserIsEligible", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Override
    public ReturnT<Boolean> queryUserIsEligible(@RequestParam(value = "userId") long userId) {
        ReturnT<Boolean> returnT = new ReturnT<>();
        ReturnT result = feignUserServiceClient.cityMasterLevel(userId);
        if (result != null) {
            int statusSuccess=200;
            if (result.getCode()==statusSuccess) {
                returnT.returnSuccess(true);
            } else {
                returnT.returnFail(result.getMsg());
            }
        }
        return returnT;
    }


    */
/**
     * cityType 城主 副城主1 副城主2
     * 确认攻打接口 -- 报名参与正副城主竞选资格条件
     *//*

    @Log(prefix = "报名参与正副城主竞选资格条件", value = LogTypeEnum.ALL)
    @RequestMapping(method = RequestMethod.POST, value = "/m2.0/citymaster/save/applycitymaster/submit", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Override
    public ReturnT<Boolean> submit(@RequestParam(value = "userId") long userId, @RequestParam(value = "cityId") long cityId, @RequestParam(value = "cityName") String cityName, @RequestParam(value = "cityType") Integer cityType, @RequestParam(value = "mobile") String mobile, @RequestParam(value = "brandId",required=false) Integer brandId) {
        ReturnT<Boolean> returnT = new ReturnT<>();
        try {

            //竞选条件
            ReturnT result = feignUserServiceClient.cityMasterLevel(userId);
            if (result.getCode() != 200) {
                returnT.returnFail(result.getMsg());
                return returnT;
            }


            Date currentTime = new Date();
            Date startTime = getDateString(getStringDate(currentTime) + propertiesConfig.getStartTime());
            Date endTime = getDateString(getStringDate(currentTime) + propertiesConfig.getEndTime());
            //判断当前时间是否在[startTime, endTime]区间，注意时间格式要一致
            if (!isEffectiveDate(currentTime, startTime, endTime)) {
                returnT.returnFail("城主竞选攻打时间在早上08点到下午22点之间开放.");
                return returnT;
            }


            //查询当前用户是否已经报名
            Query query2 = new Query();
            query2.put("userId", userId);
            query2.put("applyStatus", ApplyCityStatus.CS1.getValue());
            ApplyCityMasterDTO applyCityMasterDTO2 = applyCityMasterMapper.getCurrentUserIsAlreadyApply(query2);
            if (applyCityMasterDTO2 != null && applyCityMasterDTO2.getApplyStatus().equals(ApplyCityStatus.CS1.getValue())) {
                String msg= MessageFormat.format("您已经参与{0}市竞选啦，不能再参与竞选啦",applyCityMasterDTO2.getCityName());
                returnT.returnFail(msg);
                return returnT;
            }


            //查询当前用户是否已经是城主
            Query query3 = new Query();
            query3.put("userId", userId);
            query3.put("applyStatus", ApplyCityStatus.CS2.getValue());
            ApplyCityMasterDTO applyCityMasterDTO3 = applyCityMasterMapper.getCurrentUserIsAlreadyApply(query3);
            if (applyCityMasterDTO3 != null && applyCityMasterDTO3.getApplyStatus().equals(ApplyCityStatus.CS2.getValue())) {
                String msg= MessageFormat.format("您已经是{0}城主啦，不能再参与啦",applyCityMasterDTO3.getCityName());
                returnT.returnFail(msg);
                return returnT;
            }

            //save
            saveApplyCityMaster(userId, cityId, cityName, cityType, ApplyCityStatus.CS1.getValue(),mobile,brandId, null, null);

            returnT.returnSuccess(true);

        } catch (Exception e) {
            returnT.returnFail(e.getMessage());
        }
        return returnT;
    }


    */
/**
     * 城主save
     *
     * @param userId
     * @param cityId
     * @param cityName
     * @param cityType
     *//*

    private void saveApplyCityMaster(long userId, long cityId, String cityName, Integer cityType, Integer applyStatus,String mobile,Integer brandId, Date electionTime, Date expiryTime) {
        //报名成功
        Query query = new Query();
        query.put("userId", userId);
        query.put("cityId", cityId);
        query.put("cityName", cityName);
        query.put("cityType", cityType);
        query.put("applyStatus", applyStatus);
        query.put("mobile", mobile);
        query.put("brandId", brandId);
        query.put("electionTime", electionTime);
        query.put("expiryTime", expiryTime);
        applyCityMasterMapper.save(query);
    }


    */
/**
     * 查询用户是否已经参与报名接口  确认攻打  退出争夺
     *
     * @param userId
     * @return
     *//*

    @Log(prefix = "查询用户是否已经参与报名接口", value = LogTypeEnum.ALL)
    @RequestMapping(method = RequestMethod.POST, value = "/m2.0/citymaster/query/isncomeDetails/getCurrentUserIsApplyCampaign", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Override
    public ReturnT<Boolean> getCurrentUserIsApplyCampaign(@RequestParam(value = "userId") long userId, @RequestParam(value = "cityId") long cityId, @RequestParam(value = "cityType") Integer cityType) {
        ReturnT<Boolean> returnT = new ReturnT<>();
        try {
            Optional<ApplyCityMasterDTO> optionalApplyCityMasterDTO = Optional.ofNullable(getApplyCityMasterDTO(userId, cityId, cityType));
            if (optionalApplyCityMasterDTO.isPresent()) {
                //已报名  退出竞选
                returnT.returnSuccess(true);
            } else {
                //未报名  参与竞选
                returnT.returnSuccess(false);
            }

        } catch (Exception e) {
            //未报名  参与竞选
            returnT.returnFail(e.getMessage());
        }
        return returnT;

    }


    */
/**
     * 查询登录用户对应的城市是否已经报名
     *
     * @param userId
     * @param cityId
     * @param cityType
     * @return
     *//*

    private ApplyCityMasterDTO getApplyCityMasterDTO(@RequestParam(value = "userId") long userId, @RequestParam(value = "cityId") long cityId, @RequestParam(value = "cityType") Integer cityType) {
        Query query = new Query();
        query.put("userId", userId);
        query.put("cityId", cityId);
        query.put("cityType", cityType);
        query.put("applyStatus", ApplyCityStatus.CS1.getValue());
        return applyCityMasterMapper.getCurrentUserIsApplyCampaign(query);
    }


    */
/**
     * 退出竞选接口 -- 名单
     *//*

    @Log(prefix = "退出竞选接口", value = LogTypeEnum.ALL)
    @RequestMapping(method = RequestMethod.POST, value = "/m2.0/citymaster/query/applycitymaster/exitCampaign", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Override
    public ReturnT<Boolean> exitCampaign(@RequestParam(value = "userId") long userId, @RequestParam(value = "cityId") long cityId, @RequestParam(value = "cityType") Integer cityType) {
        ReturnT<Boolean> returnT = new ReturnT<>();
        try {

            Optional.ofNullable(getApplyCityMasterDTO(userId, cityId, cityType))
                    .map((x) -> {
                        updateApplyCityMaster(x.getId(), ApplyCityStatus.CS5.getValue(), null, null, null);
                        returnT.returnSuccess(true);
                        return returnT;
                    })
                    .orElseGet(()->{
                        throw  new RuntimeException("退出失败");
                    })
            ;

        } catch (Exception e) {
            returnT.returnFail(e.getMessage());
        }
        return returnT;
    }


    */
/**
     * 查询竞选的用户名单
     *
     * @param cityId
     * @param cityType
     * @return
     *//*

    @Log(prefix = "查询竞选的用户名单", value = LogTypeEnum.ALL)
    @RequestMapping(method = RequestMethod.POST, value = "/m2.0/citymaster/query/applycitymaster/getCampaignUser", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Override
    public ReturnT<CityDetailModel> getCampaignUser(@RequestParam(value = "cityId") Integer cityId, @RequestParam(value = "cityType") Integer cityType, @RequestParam(value = "loginUserId", required = false) Long loginUserId) {
        ReturnT<CityDetailModel> returnT = new ReturnT<>();
        CityDetailModel model = new CityDetailModel();
        try {
            List<CampaignListDTO> list = getCampaignUserList(cityId, cityType);

            //竞选报名
            List<CampaignListDTO> result = list.stream()
                    .filter((x) -> (x.getApplyStatus().equals(ApplyCityStatus.CS1.getValue())))
                    .limit(10).collect(Collectors.toList());

            //排名
            boolean isExist = list.stream().anyMatch((x) -> x.getUserId().equals(loginUserId));
            if (isExist) {
                AtomicInteger paiMing = new AtomicInteger(1);
                for (CampaignListDTO item : list) {
                    if (item.getUserId().equals(loginUserId)) {
                        model.setRanking(paiMing.getAndIncrement());
                        break;
                    } else {
                        paiMing.getAndIncrement();
                    }

                }
            }

            model.setList(result);
            returnT.returnSuccess(model);

        } catch (Exception e) {
            returnT.returnFail(e.getMessage());
        }
        return returnT;
    }


    */
/**
     * 今天有多少城主到期
     *//*

    @Log(prefix = "今天有多少城主到期", value = LogTypeEnum.ALL)
    @RequestMapping(method = RequestMethod.POST, value = "/m2.0/citymaster/query/cityRevenueRanking/getHowMuchDuebyToday", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Override
    public ReturnT<Integer> getHowMuchDuebyToday() {
        ReturnT<Integer> returnT = new ReturnT<>();
        Integer count = applyCityMasterMapper.getHowMuchDuebyToday();
        returnT.returnSuccess(count);
        return returnT;
    }


    */
/**
     * 查询竞选列表 1 报名 2 当选 3 没当选 4 下台  5 退出争夺
     *报名 1 当选 2 都查询出来
     * @param cityId
     * @param cityType
     * @return
     *//*

    private List<CampaignListDTO> getCampaignUserList(@RequestParam(value = "cityId") long cityId, @RequestParam(value = "cityType") Integer cityType) {
        List<CampaignListDTO> result = new ArrayList<>();
        List<Integer> status = new ArrayList<>();
        status.add(ApplyCityStatus.CS1.getValue());
        status.add(ApplyCityStatus.CS2.getValue());
        Query query = new Query();
        query.put("ids", status);
        query.put("cityId", cityId);
        query.put("cityType", cityType);
        //查询参与这个城市报名的用户
        List<ApplyCityMasterDTO> list = applyCityMasterMapper.getCampaignByList(query);
        if (!CollectionUtils.isEmpty(list)) {

            list.stream().forEach(x -> getCampaignListDTOS(cityType, result, x));

            List<CampaignListDTO> response = result.stream().sorted(Comparator.comparingInt(CampaignListDTO::getTeamNumber).reversed()).collect(Collectors.toList());
            return response;
        }
        return result;
    }


    */
/**
     * @param cityType
     * @param result
     * @param x
     * @return
     *//*

    private List<CampaignListDTO> getCampaignListDTOS(Integer cityType, List<CampaignListDTO> result, ApplyCityMasterDTO x) {
        CampaignListDTO dto = new CampaignListDTO();
        //查询用户信息
        Optional<TUser> optionalTUser = Optional.ofNullable(feignUserServiceClient.getUserID(x.getUserId()));
        if (optionalTUser.isPresent()){
            dto.setUserName(optionalTUser.get().getFullname());
            dto.setUserHeaderUrl(optionalTUser.get().getUserHeadUrl());
            dto.setUserLevel(optionalTUser.get().getGrade());
        }
        //排名
        dto.setCityType(x.getCityType());
        dto.setUserId(x.getUserId());
        dto.setCityId(x.getCityId());
        dto.setCityName(x.getCityName());
        dto.setApplyStatus(x.getApplyStatus());
        dto.setId(x.getId());
        dto.setElectionTime(x.getElectionTime() != null ? x.getElectionTime() : null);
        dto.setExpiryTime(x.getExpiryTime() != null ? x.getElectionTime() : null);
        dto.setMobile(x.getMobile());
        dto.setBrandId(x.getBrandId());

        //团队人数 直推+间推
        Integer count1 = feignUserServiceClient.getSonUser(x.getUserId().toString(), 1, 15);
        //城主
        if (cityType.equals(ApplyCityType.CT1.getValue())) {
            Integer count2 = feignUserServiceClient.getSonUser(x.getUserId().toString(), 2, 15);
            //总人数=直推人数+间推人数
            Integer count = count1 + count2;
            dto.setTeamNumber(count);
        } else {
            dto.setTeamNumber(count1);
        }
        result.add(dto);
        return result;
    }


    */
/**
     *
     *//*

    @RequestMapping(method = RequestMethod.POST, value = "/m2.0/citymaster/query/schedulerTaskCityMaster", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public boolean schedulerTaskCityMaster() {
        log.info("定时任务开始执行");
        try {
            if (checkIp()) {
                log.info("ip地址拿到执行啦");
                long begin = System.currentTimeMillis();
                Query queryCityConfig = new Query();
                queryCityConfig.put("cityStatus", CityConfigStatus.CCS2.getValue());
                Optional<List<CityConfigDTO>> queryList = Optional.ofNullable(cityConfigMapper.getCityByCityStatus(queryCityConfig));
                if (queryList.isPresent()) {
                    queryList.get().stream().forEach((x) -> {
                        filterCityMaster(x, ApplyCityType.CT1.getValue());  //城主
                        filterCityMaster(x, ApplyCityType.CT2.getValue());  //副城主1
                        filterCityMaster(x, ApplyCityType.CT3.getValue());  //副城主2
                    });
                    log.info("schedulerTaskCityMaster耗时:" + (System.currentTimeMillis() - begin));

                }
            }else{
                log.info("地址不正确");
            }

        } catch (Exception e) {
            String msg = MessageFormat.format("schedulerTaskCityMasterException:{0}", e.getMessage());
            log.info(msg);
        }
        log.info("定时任务结束执行");
        return true;
    }


    */
/**
     * @return
     *//*

    private boolean checkIp() {
        try {
            String ip = InetAddress.getLocalHost().getHostAddress();
            String configIp = propertiesConfig.getScheduleIp();
            if (StringUtils.isEmpty(ip)) {
                log.info("城主ip地址没有拿到");
            }
            if (StringUtils.isEmpty(configIp)) {
                log.info("城主没有拿到configIp");
            }
            log.info("定时任务城主ip地址{} 配置文件地址 {}", ip, configIp);
            if (configIp.indexOf(ip) >= 0) {
                return true;
            }
        } catch (Exception e) {
            log.info("checkIp异常啦" + e.getMessage());

        }
        return false;
    }

    */
/**
     * 筛选城主处理器   1 报名 2 当选 3 没当选 4 下台  5退出争夺
     *
     * @param cityConfigDTO
     * @param cityType
     *//*

    private Boolean filterCityMaster(CityConfigDTO cityConfigDTO, Integer cityType) {
        Long cityId = cityConfigDTO.getId();
        List<Integer> status = new ArrayList<>();
        status.add(ApplyCityStatus.CS2.getValue());
        Query query2 = new Query();
        query2.put("ids", status); //当先
        query2.put("cityId", cityId);
        query2.put("cityType", cityType);
        List<ApplyCityMasterDTO> list = applyCityMasterMapper.getCampaignByList(query2);
        if (!CollectionUtils.isEmpty(list)) {

            ApplyCityMasterDTO applyCityMasterDTO = list.get(0);
            Date nowTime = new Date();
            Date endTime = applyCityMasterDTO.getExpiryTime();
            //判断日期是否相同,只判断年月是否相同
            if (!isSameDate(nowTime, endTime)) {
                return true;
            }
        }

        //筛选处理  查询报名用户和当选  cityId 当选和报名的
        List<CampaignListDTO> result = getCampaignUserList(cityId, cityType);
        if (!CollectionUtils.isEmpty(result)) {

            Optional<CampaignListDTO> optionalCampaignListDTO = result.stream().findFirst();
            //取出报名的第一名
            if (optionalCampaignListDTO.isPresent()) {
                CampaignListDTO campaignListDTO = optionalCampaignListDTO.get();
                //查询的第一名已经是城主
                if (campaignListDTO.getApplyStatus().equals(ApplyCityStatus.CS2.getValue())) {

                    //update 那么将当前城主下台
                    updateApplyCityMaster(campaignListDTO.getId(), ApplyCityStatus.CS4.getValue(), null, null, null);

                    //save
                    Date electionTime = getDateString(getStringDate(new Date()) + propertiesConfig.getElectionTime());
                    Date expiryTime = getNextDay(electionTime, +15);
                    saveApplyCityMaster(campaignListDTO.getUserId(), campaignListDTO.getCityId(), campaignListDTO.getCityName(), campaignListDTO.getCityType(), ApplyCityStatus.CS2.getValue(), campaignListDTO.getMobile(), campaignListDTO.getBrandId(), electionTime, expiryTime);

                } else {

                    //update  更新用户为城主
                    Date electionTime = getDateString(getStringDate(new Date()) + propertiesConfig.getElectionTime());
                    Date expiryTime = getNextDay(electionTime, +15);
                    updateApplyCityMaster(campaignListDTO.getId(), ApplyCityStatus.CS2.getValue(), electionTime, expiryTime, null);
                }

                //过滤掉已经处理的
                List<CampaignListDTO> returnResult = result.stream().filter((x) -> !(x.getId().equals(campaignListDTO.getId()))).collect(Collectors.toList());

                returnResult.stream().forEach((x) -> {

                    //城主
                    if (x.getApplyStatus().equals(ApplyCityStatus.CS2.getValue())) {
                        //update 那么将当前城主下台
                        updateApplyCityMaster(x.getId(), ApplyCityStatus.CS4.getValue(), null, null, new Date());

                    } else {
                        //update 将没有当选的用户
                        updateApplyCityMaster(x.getId(), ApplyCityStatus.CS3.getValue(), null, null, null);

                    }

                });
            }

        }

        //更新处理Config
        Query query = new Query();
        query.put("cityId", cityId);
        query.put("applyStatus", ApplyCityStatus.CS2.getValue());
        List<ApplyCityMasterDTO> response = applyCityMasterMapper.getCityMasterAndDeputy(query);
        if (!CollectionUtils.isEmpty(response)) {

            //城主 1
            List<ApplyCityMasterDTO> cityMaster = response.stream().filter((x) -> x.getCityType().equals(ApplyCityType.CT1.getValue())).collect(Collectors.toList());

            //副城主2
            List<ApplyCityMasterDTO> cityDeputy = response.stream().filter((x) -> x.getCityType().equals(ApplyCityType.CT2.getValue())).collect(Collectors.toList());

            //副城主3
            List<ApplyCityMasterDTO> cityDeputy2 = response.stream().filter((x) -> x.getCityType().equals(ApplyCityType.CT3.getValue())).collect(Collectors.toList());

            //更新城市存在城主
            Query updateCityConfig = new Query();
            updateCityConfig.put("id", cityId);
            updateCityConfig.put("isCityMaster", cityMaster.size() > 0 ? true : false);
            updateCityConfig.put("isCityDeputy1", cityDeputy.size() > 0 ? true : false);
            updateCityConfig.put("isCityDeputy2", cityDeputy2.size() > 0 ? true : false);
            cityConfigMapper.updateCityMasterIsExist(updateCityConfig);
        }
        return true;

    }


    */
/**
     * update
     *
     * @param id
     * @param applyStatus
     * @param electionTime
     * @param expiryTime
     *//*

    private void updateApplyCityMaster(Long id, Integer applyStatus, Date electionTime, Date expiryTime, Date downTime) {
        Query query = new Query();
        query.put("id", id);
        query.put("applyStatus", applyStatus);
        query.put("electionTime", electionTime);
        query.put("downTime", downTime);
        query.put("updateTime", new Date());
        query.put("expiryTime", expiryTime); //到期时间
        applyCityMasterMapper.update(query);
    }


}
*/
